#include "ThreadPool.h"

void ThreadPool::threadFunc(ThreadPool *pool)
{
    pool->_isRunning = true;
    while (pool->_isRunning)
    {
        // 智能指针自动销毁
        unique_ptr<Task> task(pool->getTask());

        if (task)
        {
            task->process(nullptr);
        }
    }
}

void ThreadPool::init()
{
    for (size_t idx{}; idx < _poolSize; idx++)
    {
        _threads.emplace_back(thread(&ThreadPool::threadFunc, this));
    }
    cout << "Thread pool is ready..." << endl;
}

ThreadPool::ThreadPool(size_t poolSize, size_t taskSize)
    : _isRunning{false}, _poolSize{poolSize}, _taskSize{taskSize}, _threads(poolSize), _tasks{_taskSize}
{
    init();
}

void ThreadPool::addTask(Task *task)
{
    _tasks.addTask(task);
}

Task *ThreadPool::getTask()
{
    return _tasks.front();
}

void ThreadPool::shutdown()
{
    _isRunning = false;
    _tasks.wakeup();
    for (thread &th : _threads)
    {
        if (th.joinable())
        {
            th.join();
        }
    }
    cout << "all thread is over..." << endl;
}
